//index.js
 
Page({
  data: {
    nowTime: "",
    date: '2018-10-01',
    jieshuriqi: "请选择活动结束日期",
    kaishiriqi: "请选择活动开始日期",
    time: '12:00',
    dateTimeArray: null,
    dateTime: null,
    dateTimeArray1: null,
    dateTimeArray2: null,
    dateTime1: null,
    dateTime2: null,
    startYear: 2000,
    endYear: 2050,
    // 图片列表
    images: [],
    // 视频
    video: '',
    num: "0", //初始活动人数
    selectShow: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    selectData: [], //下拉列表的数据
    tishi: "请选择",
    startDate: '',
    endDate: "",
    title: "",
    img: "111",
    pulishData: {
      token: ""
    },
    addActi: {
      token: "",
      attack_id: "",
      name: "",
      price: "",
      img: [],
      imgtype: "",
      start_time: "",
      end_time: ""
    },
    video_img: "",

    imgPra: {
      uid_type: 2,
      path_type: "",
      uid: "",
      token: "",
      cover_path: '',
      path: ""
    }
  },
  //活动标题
  titleBlur: function (e) {
    let addActiName = 'addActi.name';
    this.setData({
      [addActiName]: e.detail.value
    })
  },
  //价格
  priceBlur(e) {
    let addActiPrice = 'addActi.price';
    this.setData({
      [addActiPrice]: e.detail.value
    })
  },
  //开始
  changeDateTime1(e) {
    var temp = e.detail.value
    var month = temp[1] + 1
    var day = temp[2] + 1
    var str = '20' + temp[0] + '-' + month + '-' + day + ' ' + temp[3] + ':' + temp[4]
    //获取当前时间
    var date = new Date();
    var year = date.getFullYear().toString(); //获取当前年份  
    var mon = (date.getMonth() + 1).toString(); //获取当前月份  
    var da = date.getDate().toString(); //获取当前日  
    var h = date.getHours().toString(); //获取小时  
    var m = date.getMinutes().toString(); //获取分钟 
    function timeAdd0(str) {
      if (str.length <= 1) {
        str = '0' + str;
      }
      return str
    }
    year = timeAdd0(year)
    mon = timeAdd0(mon)
    da = timeAdd0(da)
    h = timeAdd0(h)
    m = timeAdd0(m)
    let dangqian = year + "-" + mon + '-' + da + ' ' + h + ':' + m
    if (dangqian) {
      this.setData({
        dateTime1: e.detail.value,
        kaishiriqi: dangqian
      })
    } else {
      let addActiStart_time = 'addActi.start_time';
      this.setData({
        dateTime1: e.detail.value,
        [addActiStart_time]: str
      });
    }
  },
  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1,
      dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    let aa = this.data.dateTimeArray1[0][arr[0]] + "-" + this.data.dateTimeArray1[1][arr[1]] + "-" + this.data.dateTimeArray1[2][arr[2]] + "   " + this.data.dateTimeArray1[3][arr[3]] + ":" + this.data.dateTimeArray1[4][arr[4]];
    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr,
      kaishiriqi: aa
    });
  },
  //结束
  changeDateTime2(e) {
    var temp = e.detail.value
    var month = temp[1] + 1
    var day = temp[2] + 1
    var str = '20' + temp[0] + '-' + month + '-' + day + '' + temp[3] + ':' + temp[4]
    let addActiEnd_time = 'addActi.end_time';
    if (this.data.kaishiriqi < this.data.jieshuriqi) {
      this.setData({
        dateTime2: e.detail.value,
        [addActiEnd_time]: str
      });
    } else {
      wx.showToast({
        title: '请选择正确的时间区间',
        icon: 'none',
        duration: 3000,
        mask: true
      })
      this.setData({
        jieshuriqi: ""
      })
    }
    // compareDate(this.data.kaishiriqi, this.data.jieshuriqi)
  },
  changeDateTimeColumn2(e) {
    var arr = this.data.dateTime2;
    var dateArr = this.data.dateTimeArray2;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    let bb = this.data.dateTimeArray2[0][arr[0]] + "-" + this.data.dateTimeArray2[1][arr[1]] + "-" + this.data.dateTimeArray2[2][arr[2]] + "  " + this.data.dateTimeArray2[3][arr[3]] + ":" + this.data.dateTimeArray2[4][arr[4]]
    this.setData({
      dateTimeArray2: dateArr,
      dateTime2: arr,
      jieshuriqi: bb
    });

  },
  // 点击下拉显示框
  selectTap() {
    this.setData({
      selectShow: !this.data.selectShow
    });
  },
  // 点击下拉列表
  optionTap(e) {
    let title = e.currentTarget.dataset.title; //获取点击的下拉列表的下标
    let acID = e.currentTarget.dataset.id; //获取点击的下拉列表的下标
    let addActiAttack_id = 'addActi.attack_id';
    this.setData({
      tishi: title,
      selectShow: !this.data.selectShow,
      [addActiAttack_id]: acID
    });
  },
  // 图片操作的具体函数
  ImageOperator(e) {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        // 上传的图片数据
        const imgList = res.tempFilePaths;
        // 原始的图片数据
        const imageList = this.data.images;
        // 原来的图片数量
        let imageLenght = imageList.length;
        // 当前的图片数量
        let nowLenght = imgList.length;
        if (imageLenght == 9) {
        }
        if (imageLenght < 9) {
          let images = [];
          // 获取缺少的图片张数
          let residue = 9 - imageLenght;
          // 如果缺少的张数大于当前的的张数  
          if (residue >= nowLenght) {
            // 直接将两个数组合并为一个  
            images = imageList.concat(imgList);
          } else {
            // 否则截取当前的数组一部分  
            images = imageList.concat(imgList.slice(0, residue));
          }
          this.setData({
            images
          })
        }
      }
    })
  },
  // 图片获取
  chooseImage2(e) {
    var that = this;
    let path_type = "imgPra.path_type";
    this.setData({
      [path_type]: e.currentTarget.dataset.imgtype
    })
    var imgPraTemp = 'addActi.imgtype'
    that.setData({
      [imgPraTemp]: 1
    })
    // wx.chooseImage({
    //   count: 9, // 默认9
    //   sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    //   sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    //   success: res=>{
    //     var tempFilePaths = res.tempFilePaths
    //     var len = tempFilePaths.length;
    //     that.setData({
    //       images: tempFilePaths
    //     })
    //     for (var i = 0; i < len; i++) {
    //      wx.request({
    //       url: tempFilePaths[i],
    //       method: 'GET',
    //       responseType: 'arraybuffer',
    //       success: function (res) {
    //         var base64 = wx.arrayBufferToBase64(res.data);
    //         var imgPraTemp = 'imgPra.path'
    //         that.setData({
    //           [imgPraTemp]: base64
    //         })
    //         that.upImg()
    //       }
    //     });
    //     }
    //   }
    // })
    if (this.data.images.length == 0) {
      wx.showToast({
        title: '视频和图片只能选择上传一种类型!',
        icon: 'none',
        duration: 4000,
        success: res => {
          wx.chooseImage({
            count: 9, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: res => {
              var tempFilePaths = res.tempFilePaths
              var len = tempFilePaths.length;
              that.setData({
                images: tempFilePaths
              })
              for (var i = 0; i < len; i++) {
                wx.request({
                  url: tempFilePaths[i],
                  method: 'GET',
                  responseType: 'arraybuffer',
                  success: function (res) {
                    var base64 = wx.arrayBufferToBase64(res.data);
                    var imgPraTemp = 'imgPra.path'
                    that.setData({
                      [imgPraTemp]: base64
                    })
                    that.upImg()
                  }
                });
              }
            }
          })
        }
      })
    } else {
      this.ImageOperator()
    }
  },
  // 删除图片
  deleteImage(event) {
    //获取数据绑定的data-id的数据
    const nowIndex = event.currentTarget.dataset.id;
    let images = this.data.images;
    images.splice(nowIndex, 1);
    this.setData({
      images: images
    })
    upPics(this.data.imgPra).then(res => {
    })
  },
  // 预览图片
  previewIamge(event) {
    const nowIndex = event.currentTarget.dataset.id;
    const images = this.data.images;
    wx.previewImage({
      current: images[nowIndex], //当前预览的图片
      urls: images, //所有要预览的图片
    })
  },
  unique(arr) {
    return Array.from(new Set(arr))
  },
  //图片上传
  upImg() {
    upPics(this.data.imgPra).then(res => {
      res.datas.id ? this.data.addActi.img.push(res.datas.id) : '';
    })
  },
  //上传视频
  chooseVideo2(e) {
    var that = this;
    let vide = 'imgPra.path_type';
    that.setData({
      [vide]: vide,
    });
    var imgPraTemp = 'addActi.imgtype'
    that.setData({
      [imgPraTemp]: 2
    })
    // 弹层  
    wx.showToast({
      title: '视频和图片只能选择上传一种类型!',
      icon: 'none',
      duration: 4000,
      success: res => {
        this.videoupdata()
        wx.chooseVideo({
          sourceType: ['album', 'camera'],
          compressed: true,
          maxDuration: 10,
          camera: 'back',
          success: res => {
            that.setData({
              video: res.tempFilePath,
            });
            wx.request({
              url: res.tempFilePath,
              method: 'GET',
              responseType: 'arraybuffer',
              success: function (res) {
                var base64 = wx.arrayBufferToBase64(res.data);
                var imgPraTemp = 'imgPra.path'
                that.setData({
                  [imgPraTemp]: base64
                })
                that.upImg()
              }
            });
          }
        })
      }
    })
    // wx.chooseVideo({
    //   sourceType: ['album', 'camera'],
    //   compressed: true,
    //   maxDuration: 10,
    //   camera: 'back',
    //   success: res => {
    //     that.setData({
    //       video: res.tempFilePath,
    //     });
    //       wx.request({
    //         url: res.tempFilePath,
    //         method: 'GET',
    //         responseType: 'arraybuffer',
    //         success: function (res) {
    //           var base64 = wx.arrayBufferToBase64(res.data);
    //           var imgPraTemp = 'imgPra.path'
    //           that.setData({
    //             [imgPraTemp]: base64
    //           })
    //           that.upImg()
    //         }
    //       }); 
    //   }
    // })
  },
  //视频方法
  videoupdata() {
  },
  // 删除视频
  videoDelete(e) {
    wx.showModal({
      title: '警告',
      content: '确定要删除该视频吗',
      success: res => {
        if (res.confirm) {
          this.setData({
            video: ''
          })
        }
      }
    })
  },
  // 表单提交事件
  publishBtn(e) {
    if (!this.data.addActi.name) {
      wx.showToast({
        title: "活动内容未填写",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (this.data.addActi.img.length == 0) {
      wx.showToast({
        title: "图片/视频未上传",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!this.data.addActi.imgtype) {
      wx.showToast({
        title: "请选择攻略",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!this.data.addActi.price) {
      wx.showToast({
        title: "价格未填写",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!this.data.addActi.start_time) {
      wx.showToast({
        title: "未填写活动开始时间",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (!this.data.addActi.end_time) {
      wx.showToast({
        title: "未填写活动结束时间",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (this.data.addActi.name && this.data.addActi.img && this.data.addActi.imgtype && this.data.addActi.price && this.data.addActi.start_time && this.data.addActi.end_time) {
      // if(  ){
      //   this.setData({

      //})
      // }
      addActivity(this.data.addActi).then(res => {
        if (res.code == 600) {
          wx.showToast({
            title: res.msg,
            success: function () {
              wx.navigateTo({
                url: '../publishlist/publishlist',
              })
            }
          })
        }
      })
    }
  },
  //减少数量
  delAmount: function (e) {
    var num = this.data.num;
    if (num > 0) {
      this.data.num--;
    }
    this.setData({
      num: this.data.num
    });
  },
  //增加数量
  addAmount: function (e) {
    var num = this.data.num;
    if (num < 50) {
      this.data.num++;
    }
    this.setData({
      num: this.data.num
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(that.data.startYear, that.data.endYear);
    var obj1 = dateTimePicker.dateTimePicker(that.data.startYear, that.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    var lastArray = obj1.dateTimeArray.pop();
    var lastTime = obj1.dateTime.pop();
    that.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      dateTimeArray1: obj1.dateTimeArray,
      dateTimeArray2: obj1.dateTimeArray,
      dateTime1: obj1.dateTime,
      dateTime2: obj1.dateTime
    });
    wx.getStorage({
      key: 'token',
      success: function (res) {
        let pulishDataToken = 'pulishData.token';
        let addActiToken = 'addActi.token';
        let imgPraToken = 'imgPra.token';
        that.setData({
          [pulishDataToken]: res.data,
          [addActiToken]: res.data,
          [imgPraToken]: res.data
        })
        businessPublish(that.data.pulishData).then(res => {
          that.setData({
            selectData: res.datas
          })
        })
      },
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (res) {
    this.videoContext = wx.createVideoContext('prew_video');
  },
  /**
   * 全屏改变
   */
  bindVideoScreenChange: function (e) {
    // var that=this
    // var status = e.detail.fullScreen;
    // var play = {
    //   playVideo: false
    // }
    // if (status) {
    //   play.playVideo = true;
    // } else {
    //   that.videoContext.pause();
    // }
    // that.setData(play);
  }

})